// 公共接口调用方法封装，支持 Promise

const { getUserToken } = require('../biztools/info');
const { tipToast } = require('../common/platform');

const ajax = (url, params, method, isAuth = true, header = {}) => {
    let _header = {
        ...header,
        'content-type': 'application/json',
    };
    if (isAuth) {
        _header = {
            ...header,
            'Authorization': `Bearer ${getUserToken()}`,
        };
    }
    return new Promise((reslove, reject) => {
        wx.request({
            url,
            method,
            timeout: 10000,
            data: {
                ...params,
            },
            header: {
                ..._header,
            },
            success(res) {
                const {
                    error_code,
                    error_message,
                    message
                } = res.data; // 500错误目前返回值只有message
                if (error_code || error_message || (message && message.toLocaleLowerCase() != 'success')) {
                    tipToast(error_message || message);
                    reslove(false);
                } else {
                    reslove(res.data);
                }
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

const get = (url, param, header) => {
    return ajax(url, param, 'GET', true, header);
};

const getNormal = (url, param, header) => {
    return ajax(url, param, 'GET', false, header);
};

const post = (url, param, header) => {
    return ajax(url, param, 'POST', true, header);
};

const postNormal = (url, param, header) => {
    return ajax(url, param, 'POST', false, header);
};

const put = (url, param, header) => {
    return ajax(url, param, 'PUT', true, header);
};

const putNormal = (url, param, header) => {
    return ajax(url, param, 'PUT', false, header);
};

const patch = (url, param, header) => {
    return ajax(url, param, 'PATCH', true, header);
};

module.exports = {
    get,
    getNormal,
    post,
    postNormal,
    put,
    putNormal,
    patch,
};